//
//  AsyncGETConnection.m
//  MyTrip
//
//  Created by zhang on 15/8/22.
//  Copyright (c) 2015年 张益. All rights reserved.
//

#import "AsyncGETConnection.h"
#import "Reachability.h"
#import "SaveTools.h"

@interface AsyncGETConnection ()<NSURLConnectionDataDelegate, NSURLConnectionDelegate>

@property (nonatomic, copy) NSString *file;

@end

@implementation AsyncGETConnection

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.receiveData = [NSMutableData data];
    }
    return self;
}

// 判断网络是否连接成功
+ (BOOL)judgeConnection
{
    Reachability *reach = [Reachability reachabilityWithHostName:@"http://www.baidu.com"];
    NetworkStatus status = [reach currentReachabilityStatus];
    if (status == NotReachable) { // 没网
        return NO;
    } else if (status == ReachableViaWWAN) { // 3G
        return YES;
    } else if (status == ReachableViaWiFi) { // wifi
        return YES;
    }
    return NO;
}





+ (instancetype)asyncGETConnectionWithURLStr:(NSString *)URLStr parameters:(NSDictionary *)parameters messageBlock:(void(^)(NSData *data))messageBlock{
    
    NSString *par = @"";
    for (NSString *key in [parameters allKeys]) {
        par = [NSString stringWithFormat:@"%@&%@=%@", par, key, [parameters objectForKey:key]];
    }
    
    URLStr = [NSString stringWithFormat:@"%@%@", URLStr, par];
    
    URLStr = [URLStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSString *file = [NSString stringWithFormat:@"%@", URLStr];
    file = [file stringByReplacingOccurrencesOfString:@"/" withString:@""];
    file = [file stringByReplacingOccurrencesOfString:@":" withString:@""];
    

    BOOL judge = [AsyncGETConnection judgeConnection];
    
    if (judge) {
//        判断有网
        AsyncGETConnection *async = [[AsyncGETConnection alloc] init];
        async.receiveBlock = messageBlock;
        [async startConnectURLStr:URLStr];
        async.file = file;
        return [async autorelease];
    }else{
        NSString *path = [SaveTools pathWithName:file directory:NSLibraryDirectory];
        
        NSFileManager *manager = [NSFileManager defaultManager];
        if ([manager fileExistsAtPath:path]) {
            NSData *data = [NSData dataWithContentsOfFile:path];
            messageBlock(data);
        }
    }
    return nil;
}



- (void)startConnectURLStr:(NSString *)URLStr{
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URLStr]];
    [request setHTTPMethod:@"GET"];
    [NSURLConnection connectionWithRequest:request delegate:self];
}


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [self.receiveData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    [SaveTools saveDataWith:self.file directory:NSLibraryDirectory data:(NSData *)self.receiveData];
    self.receiveBlock(self.receiveData);
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"%@", error);
}




@end
